<template>
  <view class="wanl-live-message">
    <view class="wanl-live-comment">
      <view class="wanl-live-comment-item">
        <scroll-view
          scroll-y="true"
          :show-scrollbar="false"
          :scroll-into-view="scrollToView"
          :scroll-with-animation="true"
          class="wanl-live-comment-item-scroll"
        >
          <!-- #ifdef APP -->
          <view class="wanl-live-comment-item-scroll-app" v-for="(item, index) in msgList" :key="index" :id="'msg' + index">
            <view class="wanl-live-comment-item-scroll-app-item">
              <text :class="[iscolor(item.form.id)]" class="app-text">{{ item.form.name }}：</text>
              <text class="app-context">{{ item.message }}</text>
            </view>
          </view>
          <!-- #endif -->

          <!-- #ifdef H5 -->
          <div class="wanl-live-comment-item-scroll-h5" v-for="(item, index) in msgList" :key="index" :id="'msg' + index">
            <div class="wanl-live-comment-item-tag">
              <text :class="[iscolor(item.form.id)]" class="mph5-text">{{ item.form.name }}：</text>
              <text class="mph5-context">{{ item.message }}</text>
            </div>
          </div>
          <!-- #endif -->

          <!-- #ifdef MP -->
          <div class="wanl-live-comment-item-scroll-mp" v-for="(item, index) in msgList" :key="index" :id="'msg' + index">
            <div class="wanl-live-comment-item-tag">
              <text :class="[iscolor(item.form.id)]" class="mph5-text">{{ item.form.name }}：</text>
              <text class="mph5-context">{{ item.message }}</text>
            </div>
          </div>
          <!-- #endif -->
        </scroll-view>
        <view class="mask" v-if="isfocur" @tap="blur()"> </view>

        <view class="comment-box">
          <input
            ref="commentInput"
            class="comment-input"
            v-model="msgText"
            placeholder="聊一聊"
            placeholder-class="placeholderClass"
            :adjust-position="true"
            confirm-type="send"
            style="flex: 1"
            @focus="handleFocus"
            @blur="handleBlur"
            @confirm="onSend"
          />

          <text class="send-btn" @click="onSend()">发送</text>

          <!-- <view class="shang-btn" @tap="openRedpacket()">
						<image src="/static/images/shang2.png" class="shang-image"></image>
					</view> -->
        </view>
      </view>
    </view>

    <uni-transition :mode-class="['slide-left']" :styles="{ position: 'absolute', left: '0', top: '-60rpx' }" :show="comingShow">
      <view class="wanl-live-coming">
        <text class="wanl-live-coming-text">{{ comingName }} 他来了他来了~</text>
      </view>
    </uni-transition>
  </view>
</template>

<script>
  import sheep from '@/sheep';
  // import uniTransition from '@/components/uni-transition/uni-transition';
  import userstore from '@/sheep/store/user.js';
  import chatstore from '@/sheep/store/chat.js';
  import { mapState, mapActions } from 'pinia';
  import socket from '@/sheep/store/socket';

  export default {
    name: 'LiveMessage',
    data() {
      return {
        msgText: '',
        scrollToView: 'msg1',
        comingShow: false,
        comingName: '',
        isfocur: false,
        watchTimer: null,
        msgList: [],
        likeList: [],
      };
    },
    props: {
      liveData: {
        type: Object,
        default: null,
      },
    },
    mounted() {
      uni.$on('live_message', this.parseMsgStatus);
      uni.$on('live_message_' + this.liveData.id, this.parseMsgStatus);
    },
    beforeUnmount() {
      uni.$off('live_message', this.parseMsgStatus);
      uni.$off('live_message_' + this.liveData.id, this.parseMsgStatus);
    },
    computed: {
      ...mapState(userstore, ['userInfo']),
      ...mapState(chatstore, ['messages', 'isConnected']),
      isClose() {
        return !this.isConnected;
      },
    },
    methods: {
      ...mapActions(socket, ['sendmsg']),

      blur() {
        // #ifdef APP
        this.$refs.commentInput.blur();
        // #endif
      },
      // 解析链接状态
      parseMsgStatus(obj) {
        //let obj = JSON.parse(msgStr);
        console.log('主播端 parseMsgStatus 收到消息', obj, '连接状态:', socket().socketIo.is_open_socket);
        switch (obj.type) {
          case 'data':
            console.log('主播端 收到data类型消息，更新在线人数');
            this.$emit('changeOnlineNum', obj.data.message);
            break;

          case 'message':
            //如果是自己发送的消息，则不展示
            if (obj.form.id == this.userInfo.id) {
              console.log('主播端 收到自己发送的消息，不展示', obj.form.id, this.userInfo.id);
              return false;
            }
            let obj1 = this.parseMsg(obj.message, obj.form, obj.createtime);
            console.log('主播端 解析后的消息对象', obj1);
            if (obj1) {
              this.msgList.push(obj1);
              console.log('主播端 消息列表更新，当前长度:', this.msgList.length);
            }

            // 修复：移除多余的空push
            // this.msgList.push();

            this.$nextTick(() => {
              this.scrollToView = `msg${this.msgList.length - 1}`;
              console.log('主播端 滚动到最新消息:', this.scrollToView);
            });

            break;

          default:
            console.log('主播端 收到未知类型消息:', obj.type);
        }
      },
      sendMsg(content, type) {
        this.sendWs('主播在直播间发了红包', 'redpacket');
        this.pushChat('主播在直播间发了红包', 'text');
      },

      // 解析消息类型,接受数据时才用，发送数据时不用。
      parseMsg(message, fromuser, createtime) {
        console.log('主播端 parseMsg 接收到的消息对象:', message, '发送者:', fromuser, '创建时间:', createtime);
        let obj = null;
        switch (message.type) {
          case 'text':
            console.log('主播端 解析文本消息:', message.content);
            obj = {
              createtime: createtime,
              is_my: false,
              message: message.content,
              message_type: message.type,
              form: fromuser,
            };
            break;
          case 'redpacket':
            // obj = {
            // 	creatime: createtime,
            // 	is_my: false,
            // 	message: message.content,
            // 	message_type: message.type,
            // 	form: fromuser
            // };
            this.emit('refisdlive');
            return false;
            break;
          case 'system_live':
            console.log('主播端 解析系统直播消息:', message.content);
            this.$emit(message.content.type, message.content);
            return false;
            break;

          case 'gift':
            console.log('主播端 解析礼物消息:', message.content);
            obj = {
              createtime: createtime,
              is_my: false,
              message: '赠送了【' + message.content.name + '】',
              message_type: message.type,
              form: fromuser,
              gift: message.content,
            };
            break;
          default:
            console.log('主播端 解析未知类型消息:', message.type, message.content);
            return false;
        }
        console.log('主播端 解析后的消息对象:', obj);
        return obj;
      },

      //用户退出
      quit() {
        //发送退出消息
        console.log('live go quit');
        // this.sendWs('', 'tc');
      },
      onSend() {
        if (this.msgText) {
          this.blur();
          this.sendWs(this.msgText);
          this.pushChat(this.msgText);
          this.msgText = '';
        }
      },
      // 发送服务数据
      async sendWs(data, type = 'text') {
        console.log('主播端 准备发送消息，类型:', type, '内容:', data, '直播间ID:', this.liveData.id);
        let msg = {
          type: 'message_live',
          data: {
            to: this.liveData.id,
          },
          message: {
            type: type, // 修复：将message_type改为type，与parseMsg中的判断一致
            content: data, // 修复：将message改为content，与parseMsg中的读取一致
          },
          form: {
            id: this.userInfo.id,
            avatar: this.userInfo.avatar,
            name: this.userInfo.nickname,
          },
        };
        let strMsg = JSON.stringify(msg);
        try {
          console.log('主播端 发送消息前的对象', msg, '连接状态:', socket().socketIo.is_open_socket);
          let res = await sheep.$api.video.livemsg({
            id: this.liveData.id,
            message_type: type,
            message: data,
          });
          console.log('主播端 发送消息内容', strMsg);
          console.log('主播端 API返回结果', res);
          if (res.error === 0) {
            console.log('主播端 API调用成功，发送WebSocket消息');
            this.sendmsg(strMsg, 'text');
            return true;
          } else {
            console.error('主播端 API调用失败，错误码:', res.error, '错误信息:', res.msg);
            uni.showToast({
              title: res.msg || '发送失败，请重试',
              icon: 'none',
            });
            return false;
          }
        } catch (error) {
          console.error('主播端 发送消息失败', error);
          uni.showToast({
            title: '发送失败，请重试',
            icon: 'none',
          });
          return false;
        }
      },
      // 发送本地数据。
      pushChat(data, type = 'text') {
        console.log('go pushChat', data, type);

        if (this.isClose) {
          uni.showToast({
            title: '您已掉线',
            icon: 'none',
          });
          return;
        }

        this.msgList.push({
          is_my: true,
          type: 'message_live',
          message_type: type,
          message: data,
          form: {
            id: this.userInfo.id,
            avatar: this.userInfo.avatar,
            name: this.userInfo.nickname,
          },
          createtime: this.dateFormat('yyyy-MM-dd hh:mm:ss'),
        });

        this.msgText = '';
        this.$nextTick(() => {
          this.scrollToView = `msg${this.msgList.length - 1}`;
        });
      },

      onMessage(msg) {
        console.log('主播端收到消息', msg);
        var message = msg.message;
        var form = msg.form;
        if (
          message.type == 'msg' ||
          message.type == 'seek' ||
          message.type == 'follow' ||
          message.type == 'like' ||
          message.type == 'review' ||
          message.type == 'text'
        ) {
          if (message.type == 'like') {
            this.likeStart();
          }

          // 处理文本消息
          if (message.type == 'text') {
            this.msgList.push({
              is_my: form.id === this.userInfo.id,
              type: 'message_live',
              message_type: 'text',
              message: message.message,
              form: form,
              createtime: this.dateFormat('yyyy-MM-dd hh:mm:ss'),
            });
          } else {
            this.msgList.push({
              form: form,
              text: message.text,
            });
          }

          this.$nextTick(() => {
            this.scrollToView = `msg${this.msgList.length - 1}`;
          });
        } else if (message.type == 'coming') {
          if (this.comingShow) {
            clearTimeout(this.watchTimer);
            this.comingShow = false;
          }
          this.comingName = form.name;
          this.openComing();
        }
      },
      openComing() {
        this.comingShow = true;
        this.watchTimer = setTimeout(() => {
          this.comingShow = false;
        }, 1000);
      },
      iscolor(id) {
        return [
          'text-blue',
          'text-white',
          'text-orange',
          'text-yellow',
          'text-brown',
          'text-olive',
          'text-green',
          'text-red',
          'text-pink',
          'text-purple',
        ][parseInt(id % 10)];
      },
      handleFocus() {
        this.isfocur = true;
        //console.log("go handleFocus");
      },
      handleBlur() {
        this.isfocur = false;
        //console.log("go handleBlur");
      },
      dateFormat(fmt) {
        let date = new Date();

        var o = {
          'M+': date.getMonth() + 1, //月份
          'd+': date.getDate(), //日
          'h+': date.getHours(), //小时
          'm+': date.getMinutes(), //分
          's+': date.getSeconds(), //秒
          'q+': Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        for (var k in o)
          if (new RegExp('(' + k + ')').test(fmt))
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        return fmt;
      },
      openRedpacket() {
        uni.navigateTo({
          url: '/pages/video/live/redpacket?id=' + this.liveData.id,
        });
        this.blur();
      },
    },
  };
</script>

<style lang="scss">
  .wanl-live-message {
    position: relative;

    .mask {
      flex: 1;
      position: absolute;
    }
  }

  /* 群组消息 */
  .wanl-live-comment {
    /* #ifndef APP */
    /*-webkit-mask: -webkit-gradient(linear,left 30%,left top,from(#000),to(transparent));*/
    /* #endif */

    margin-left: 25rpx;
    margin-right: 25rpx;
    justify-content: space-between;
    flex-direction: row;
    position: relative;
  }

  .wanl-live-comment-item {
    overflow: hidden;
    color: #ffffff;
    flex: 1;
  }

  .wanl-live-comment-item-scroll {
    /* #ifdef H5 || MP */
    max-height: 500rpx;
    min-height: 60rpx;
    /* #endif */
    /* #ifdef APP */
    height: 500rpx;
    /* #endif */
  }

  /* #ifdef H5 || MP */
  .wanl-live-comment-item-scroll-h5 {
    margin-top: 6rpx;
    overflow: hidden;
    display: flex;
  }

  .wanl-live-comment-item-scroll-mp {
    margin-bottom: 6rpx;
    overflow: hidden;
    display: block;
  }

  .wanl-live-comment-item-tag {
    background-color: rgba(0, 0, 0, 0.2);
    padding-top: 8rpx;
    padding-right: 16rpx;
    padding-bottom: 8rpx;
    padding-left: 16rpx;
    border-radius: 10rpx;
    overflow: hidden;
    display: inline-block;
  }

  /* #endif */
  .wanl-live-comment-item-scroll-app {
    flex-direction: row;
    margin-top: 6rpx;
  }

  .wanl-live-comment-item-scroll-app-item {
    background-color: rgba(0, 0, 0, 0.2);
    padding-top: 8rpx;
    padding-right: 16rpx;
    padding-bottom: 8rpx;
    padding-left: 16rpx;
    border-radius: 10rpx;
    flex-direction: row;
  }

  /* 点赞特效	 */
  .wanl-live-like {
    position: relative;
    /* #ifndef APP */
    flex: 0 0 120rpx;
    /* #endif */
    width: 120rpx;
    height: 500rpx;
  }

  /* #ifndef APP */
  .bubble {
    position: absolute;
    width: 90rpx;
    height: 90rpx;
    bottom: 0;
    background-repeat: no-repeat;
    background-size: 100%;
    transform-origin: bottom;
  }

  /* .b1 {background-image: url(/static/images/live/1.png);}
.b2 {background-image: url(/static/images/live/2.png);}
.b3 {background-image: url(/static/images/live/3.png);}
.b4 {background-image: url(/static/images/live/4.png);}
.b5 {background-image: url(/static/images/live/5.png);}
.b6 {background-image: url(/static/images/live/6.png);} */
  .bl1 {
    animation:
      bubble_1 3s linear 1 forwards,
      bubble_big_1 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl2 {
    animation:
      bubble_2 3s linear 1 forwards,
      bubble_big_2 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl3 {
    animation:
      bubble_3 3s linear 1 forwards,
      bubble_big_1 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl4 {
    animation:
      bubble_4 3s linear 1 forwards,
      bubble_big_2 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl5 {
    animation:
      bubble_5 3s linear 1 forwards,
      bubble_big_1 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl6 {
    animation:
      bubble_6 3s linear 1 forwards,
      bubble_big_3 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl7 {
    animation:
      bubble_7 3s linear 1 forwards,
      bubble_big_1 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl8 {
    animation:
      bubble_8 3s linear 1 forwards,
      bubble_big_3 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl9 {
    animation:
      bubble_9 3s linear 1 forwards,
      bubble_big_2 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl10 {
    animation:
      bubble_10 3s linear 1 forwards,
      bubble_big_1 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  .bl11 {
    animation:
      bubble_11 3s linear 1 forwards,
      bubble_big_2 0.8s linear 1 forwards,
      bubble_y 3s linear 1 forwards;
  }

  @keyframes bubble_11 {
    0% {
    }

    25% {
      margin-left: -20rpx;
    }

    50% {
      margin-left: -20rpx;
    }

    100% {
      margin-left: -36rpx;
    }
  }

  @keyframes bubble_10 {
    0% {
    }

    25% {
      margin-left: -40rpx;
    }

    50% {
      margin-left: -40rpx;
    }

    100% {
      margin-left: -40rpx;
    }
  }

  @keyframes bubble_9 {
    0% {
    }

    25% {
      margin-left: 20rpx;
    }

    50% {
      margin-left: 20rpx;
    }

    100% {
      margin-left: 20rpx;
    }
  }

  @keyframes bubble_8 {
    0% {
    }

    25% {
      margin-left: 40rpx;
    }

    50% {
      margin-left: 40rpx;
    }

    100% {
      margin-left: 40rpx;
    }
  }

  @keyframes bubble_7 {
    0% {
    }

    25% {
      margin-left: 6rpx;
    }

    50% {
      margin-left: 2rpx;
    }

    75% {
      margin-left: 4rpx;
    }

    100% {
      margin-left: 6rpx;
    }
  }

  @keyframes bubble_6 {
    0% {
    }

    25% {
      margin-left: -6rpx;
    }

    50% {
      margin-left: -2rpx;
    }

    75% {
      margin-left: -4rpx;
    }

    100% {
      margin-left: -6rpx;
    }
  }

  @keyframes bubble_5 {
    0% {
    }

    25% {
      margin-left: 10rpx;
    }

    50% {
      margin-left: -10rpx;
    }

    75% {
      margin-left: -20rpx;
    }

    100% {
      margin-left: -40rpx;
    }
  }

  @keyframes bubble_4 {
    0% {
    }

    25% {
      margin-left: -10rpx;
    }

    50% {
      margin-left: -10rpx;
    }

    75% {
      margin-left: 40rpx;
    }

    100% {
      margin-left: 20rpx;
    }
  }

  @keyframes bubble_3 {
    0% {
    }

    25% {
      margin-left: -40rpx;
    }

    50% {
      margin-left: 20rpx;
    }

    75% {
      margin-left: 40rpx;
    }

    100% {
      margin-left: -20rpx;
    }
  }

  @keyframes bubble_2 {
    0% {
    }

    25% {
      margin-left: 40rpx;
    }

    50% {
      margin-left: 50rpx;
    }

    75% {
      margin-left: 20rpx;
    }

    100% {
      margin-left: 10rpx;
    }
  }

  @keyframes bubble_1 {
    0% {
    }

    25% {
      margin-left: -16rpx;
    }

    50% {
      margin-left: 16rpx;
    }

    75% {
      margin-left: -30rpx;
    }

    100% {
      margin-left: 30rpx;
    }
  }

  @keyframes bubble_big_1 {
    0% {
      transform: scale(0.3);
    }

    100% {
      transform: scale(1.2);
    }
  }

  @keyframes bubble_big_2 {
    0% {
      transform: scale(0.3);
    }

    100% {
      transform: scale(0.9);
    }
  }

  @keyframes bubble_big_3 {
    0% {
      transform: scale(0.3);
    }

    100% {
      transform: scale(0.6);
    }
  }

  @keyframes bubble_y {
    0% {
      margin-bottom: 0;
    }

    10% {
      margin-bottom: 0;
    }

    75% {
      opacity: 1;
    }

    100% {
      margin-bottom: 400rpx;
      opacity: 0;
    }
  }

  /* #endif */

  /* 欢迎信息 */
  .wanl-live-coming {
    margin-left: 25rpx;
    background-color: rgba(255, 86, 136, 0.7);
    padding-top: 8rpx;
    padding-right: 16rpx;
    padding-bottom: 8rpx;
    padding-left: 16rpx;
    border-radius: 10rpx;
  }

  .wanl-live-coming-text {
    color: #ffffff;
    font-size: 28rpx;
  }

  .app-text {
    font-size: 29rpx;
  }

  .app-context {
    font-size: 29rpx;
    color: #ffffff;
  }

  .mph5-text {
    font-size: 26rpx;
  }

  .mph5-context {
    font-size: 26rpx;
    color: #ffffff;
  }

  .text-white {
    color: #ffffff !important;
  }

  .text-orange {
    color: #fe6600 !important;
  }

  .text-yellow {
    color: #ffff00 !important;
  }

  .text-green {
    color: #39b54a !important;
  }

  .text-olive {
    color: #8dc63f !important;
  }

  .text-purple {
    color: #6739b6 !important;
  }

  .text-pink {
    color: #f840b1 !important;
  }

  .text-blue {
    color: #0081ff !important;
  }

  .text-brown {
    color: #a5673f !important;
  }

  .text-red {
    color: #ff243a !important;
  }

  .comment-box {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .comment-input {
    background-color: rgba(255, 255, 255, 0.2);
    margin-right: 20rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #fff;
    padding: 0rpx 30rpx;
    height: 70rpx;
    width: 500rpx;
  }

  .send-btn {
    font-size: 28rpx;
    color: white;
    height: 60rpx;

    line-height: 60rpx;
  }

  .placeholderClass {
    font-size: 28rpx;
    color: #999999;
    padding: 0rpx 30rpx;
  }

  .gift-btn,
  .shang-btn {
    width: 80rpx;
    height: 80rpx;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 30rpx;
  }

  .gift-image {
    width: 40rpx;
    height: 40rpx;
  }

  .shang-image {
    width: 44rpx;
    height: 44rpx;
  }
</style>
